import axios from 'axios'
import store from '@/store'

const request = axios.create({
  baseURL: 'http://localhost:4000',
})

request.interceptors.request.use(
  (config) => {
    let saToken = window.localStorage.getItem('token')
    let con = config.headers as any
    con['satoken'] = saToken || ''
    // 加载条
    store.commit('startLoading')
    return config
  },
  (err) => {}
)

request.interceptors.response.use(
  (response) => {
    const messageModel = response.data['messageModel']
    const message = response.data['msg']
    if (message === '') {
      store.commit('endLoading')
      return response
    }
    let messageType = response.data['code'] === 200 ? 'success' : 'error'
    if (messageModel === 'lit') {
      if (messageType === 'success') {
        store.state.useMessage?.success(message)
        store.commit('endLoading')
      } else {
        store.commit('errorLoading')
        store.state.useMessage?.error(message)
      }
    } else if (messageModel === 'big') {
      if (messageType === 'success') {
        store.state.useNotification?.success({
          content: '成功',
          meta: message || '操作成功',
          duration: 3000,
        })
        store.commit('endLoading')
      } else {
        store.state.useNotification?.error({
          content: '失败',
          meta: message || '失败',
          duration: 3000,
        })
        store.commit('errorLoading')
      }
    }

    return response
  },
  (err) => {
    store.commit('errorLoading')
    store.state.useNotification?.error({
      content: '服务器异常',
      meta: '请直接联系服务器维护人员进行处理',
      duration: 3000,
    })
  }
)

export default request
